<?php
/*
 * @分销商城
 * @功能说明：订单主业务
 * @更新说明：暂无更新
 * @文件名 OrderController.class.php
 * @编码 UTF-8
 * @创建时间 2016-1-23 下午1:48:30
 * @创建人 XING
 */
namespace bj\Controller;
use Think\Controller;

class OrderController extends ApibaseController
{
    function __construct() {
        parent::__construct();
        $this->_OrderCollectModel = D('OrderCollect');
    }

    /*
     * 分销商城_订单主页NEW
     * @date: 2015-12-25 下午4:49:04
     * @editor: XING
     */
    public function index() {
        /*参数初始化*/
        $page = I('get.page') ?: 1;
        $perpage = 10;
        $url = $output = $outtype = array();
        //获取订单状态等信息 根据订单号获取商品ID 根据商品ID获取商品来源等信息
        $sql = "SELECT DISTINCT(a.order_id),a.order_status,a.refund_expressnum,a.receive_identity,a.remark,a.nickname,a.receive_name,a.receive_mobile,a.receive_address,a.order_pay,a.add_at
				FROM fx_order_entity a
				LEFT JOIN fx_order_collect b
				ON a.order_id=b.order_id
				LEFT JOIN fx_goods_entity c
				ON b.goods_id=c.goods_id
				WHERE a.order_type=0 AND c.resource=2";
        if (I('get.order_id')) {
            $sql = $sql . " AND a.order_id ='" . I('get.order_id') . "'";
            $url['order_id'] = I('get.order_id');
        }
        if (I('get.cust_name')) {
            $sql = $sql . " AND a.nickname LIKE '%" . I('get.cust_name') . "%'";
            $url['cust_name'] = I('get.cust_name');
        }
        if (I('get.cust_mobile')) {
            $sql = $sql . " AND a.receive_mobile =" . I('get.cust_mobile');
            $url['cust_mobile'] = I('get.cust_mobile');
        }
        if ((I('get.st') > -2 && isset($_GET['st'])) && !in_array(I('get.st'), array('all', 'refund'))) {
            $sql = $sql . " AND a.order_status=" . I('get.st');
            $url['st'] = I('get.st');
        } elseif (I('get.st') == 'refund') {
            $sql = $sql . " AND a.order_status IN(5,6,7,8,9)";
            $url['st'] = I('get.st');
        }
        $list = CQuery($sql . " order by a.add_at DESC limit " . ($page - 1) * $perpage . "," . $perpage);
        $this->assign('page', setPage(count(CQuery($sql)), $perpage, $page, '?' . http_build_query($url)));
        $this->assign('getData', $list);
        $this->display('order/index');
    }


    /*
     * 分销商城_退货理由
     * @date: 2016-04-08 18:52:00
     * @editor: WENCUN
     * */
    public function refundly() {
        $custData = M('OrderEntity')
            ->where(array('order_id' => I('get.oid')))->find();
        $refunds = explode(',', getSysConfig('refundType'));
        $refundsImgs = explode(',', $custData['refund_imgs']);
        foreach ($refundsImgs as $key => $value) {
            $refundsImgs[$key] = transUrl($value);
        }
        $this->refundsImgs = $refundsImgs;
        $this->assign('refunds', $refunds);
        $this->assign('sData', $custData);
        $this->display('order/refundly');
    }

    /*
     * 分销商城_退货物流信息
     * @date: 2016-04-12 09:25:00
     * @editor: WENCUN
     * */
    public function refundwl() {
        $custData = M('OrderEntity')
            ->where(array('order_id' => I('get.oid')))->find();
        $this->assign('sData', $custData);
        $this->display('order/refundwl');
    }

    /*
     * 分销商城_订单退款
     * @date: 2015-12-29 下午5:14:13
     * @editor: XING
     */
    public function refundmon() {
        if (I('post.dosubmit')) {
            if (in_array(I('post.status'), array('8', '9')) && I('post.id')) {
                $orderMain = M('OrderEntity');
                if (I('post.status') == '8') {
                    $upsArr = array(
                        'order_status' => '8',
                    );
                    I('post.remark') ? $upsArr['refund_mark'] = trim(I('post.remark')) : '';
                    $orderMain->startTrans();
                    $orderEffect = $orderMain->lock(true)
                        ->where(array('order_id' => I('post.id'), 'order_status' => '6'))->setField($upsArr);
                    if ($orderEffect) {
                        $checkProfit = M('GoodsProfit')
                            ->where(array('order_id' => I('post.id'), 'is_profit' => '1'))->count();
                        if ($checkProfit > 0) {
                            $uBottler = M('GoodsProfit');
                            $putReback = $uBottler->lock(true)
                                ->where(array('order_id' => I('post.id'), 'is_profit' => '1'))->setField(array(
                                    'is_profit' => '2',
                                    'update_at' => time()
                                ));
                            if ($putReback) {
                                $getChargeOrder = M('PayChannel')
                                    ->where(array('order_id' => I('post.id')))->find();
                                if ($getChargeOrder) {
                                    //@todo  发起退款请求，成功后回调。
                                    $getOrderDesc = M('OrderEntity')->field('pay_money')
                                        ->where(array('order_id' => I('post.id')))->find();
                                    $reQuest = (new \service\ping\Ping)->payRefund($getChargeOrder['charge_id'], I('post.id'), $getOrderDesc['pay_money']);
                                    $dataBack = json_decode($reQuest, 1);
                                    if ($dataBack['id']) {
                                        M('PayChannel')->where(array('order_id' => I('post.id')))->setField(array(
                                            'refund_id' => $dataBack['id']
                                        ));
                                        if ($getChargeOrder['pay_channel'] == 'alipay') {
                                            $url = str_replace('Open url for refund: ', '', $dataBack['failure_msg']);
                                            putlog('申请退款通过，提交支付页面 ', 'OrderController', 'refundmon');

                                            echo json_encode(array('msg' => 'success', 'url' => $url, 'type' => 'url'));
                                            exit;
                                        } elseif ($getChargeOrder['pay_channel'] == 'wx_pub') {
                                            putlog('申请退款通过，提交银行处理 ', 'OrderController', 'refundmon');
                                            echo json_encode(array('msg' => '操作成功', 'type' => 'other', 'code' => '1'));
                                        }
                                        $uBottler->commit();
                                        $orderMain->commit();
                                        //curl('http://192.168.0.132/jsssdk/refund',array('order_id'=>I('post.id')));
                                        curl('http://wap.hipaygo.cn/jsssdk/refund', array('order_id' => I('post.id')));
                                        $this->showtips('退款成功');
                                    } else {
                                        $orderMain->rollback();
                                        $uBottler->rollback();
                                        $this->showtips('操作失败');
                                        jsonRespons(0, '退款Api发起失败');
                                    }
                                } else {
                                    $orderMain->rollback();
                                    $uBottler->rollback();
                                    $this->showtips('操作失败');
                                }
                            } else {
                                $orderMain->rollback();
                                $uBottler->rollback();
                                $this->showtips('操作失败');
                            }
                        } else {
                            $uBottler = M('GoodsProfit');
                            $putReback = $uBottler->lock(true)
                                ->where(array('order_id' => I('post.id')))->where('is_profit IN(0,3)')->setField(array(
                                    'is_profit' => '-1',
                                    'update_at' => time()
                                ));
                            if ($putReback) {
                                $getChargeOrder = M('PayChannel')
                                    ->where(array('order_id' => I('post.id')))->find();
                                if ($getChargeOrder) {
                                    //@todo  发起退款请求，成功后回调。
                                    $getOrderDesc = M('OrderEntity')->field('pay_money')
                                        ->where(array('order_id' => I('post.id')))->find();
                                    $reQuest = (new \service\ping\Ping)->payRefund($getChargeOrder['charge_id'], I('post.id'), $getOrderDesc['pay_money']);
                                    $dataBack = json_decode($reQuest, 1);
                                    if ($dataBack['id']) {
                                        M('PayChannel')->where(array('order_id' => I('post.id')))->setField(array(
                                            'refund_id' => $dataBack['id']
                                        ));
                                        if ($getChargeOrder['pay_channel'] == 'alipay') {
                                            $url = str_replace('Open url for refund: ', '', $dataBack['failure_msg']);
                                            putlog('申请退款通过，提交支付页面 ', 'OrderController', 'refundmon');

                                            echo json_encode(array('msg' => 'success', 'url' => $url, 'type' => 'url'));
                                            exit;
                                        } elseif ($getChargeOrder['pay_channel'] == 'wx_pub') {
                                            putlog('申请退款通过，提交银行处理 ', 'OrderController', 'refundmon');
                                            echo json_encode(array('msg' => '操作成功', 'type' => 'other', 'code' => '1'));
                                        }
                                        $uBottler->commit();
                                        $orderMain->commit();
                                        //curl('http://192.168.0.132/jsssdk/refund',array('order_id'=>I('post.id')));
                                        curl('http://wap.hipaygo.cn/jsssdk/refund', array('order_id' => I('post.id')));
                                        $this->showtips('退款成功');
                                    } else {
                                        $orderMain->rollback();
                                        $uBottler->rollback();
                                        $this->showtips('操作失败');
                                        jsonRespons(0, '退款Api发起失败');
                                    }
                                } else {
                                    $orderMain->rollback();
                                    $uBottler->rollback();
                                    $this->showtips('操作失败');
                                }
                            } else {
                                $orderMain->rollback();
                                $uBottler->rollback();
                                $this->showtips('操作失败');
                            }
                        }
                    } else {
                        $orderMain->rollback();
                        $this->showtips('操作失败');
                    }
                } else {
                    $orderEffect = $orderMain
                        ->where(array('order_id' => I('post.id'), 'order_status' => '6'))->setField(array(
                            'order_status' => '7',
                        ));
                    if ($orderEffect) {
                        $this->showtips('操作成功，已拒绝退款');
                    } else {
                        $this->showtips('操作失败');
                    }
                }
            } else {
                $this->showtips('参数有误，操作失败');
            }
        } elseif (I('get.oid')) {
            $custData = M('OrderEntity')
                ->where(array('order_id' => I('get.order_id')))->find();
            $this->assign('sData', $custData);
            $this->display('order/refundmon');
        }
    }

    /*
     * 分销商城_订单发货
     * @date: 2016-04-27 11:52:00
     * @editor: WENCUN
     */
    public function send() {
        if (I('post.dosubmit') && I('post.id')) {
            //物流单号非空验证
            if (!I('post.express')) {
                $this->showtips('请填写有效的物流单号');
            }
            $sql = "SELECT b.goods_id,b.pay_nums
					FROM fx_order_entity a
					LEFT JOIN fx_order_collect b
					ON a.order_id=b.order_id
					LEFT JOIN  fx_goods_entity c
					ON b.goods_id=c.goods_id
					WHERE a.order_type=0 AND a.order_id=" . I('post.id') . " AND c.resource=2";
            $goodsId = CQuery($sql);
            $orderCollect = M('OrderCollect');
            foreach ($goodsId as $key => $value) {
                $setExpress = $orderCollect->where(array('order_id' => I('post.id'), 'goods_id' => $value['goods_id']))->setField(array(
                    'express_name' => I('post.express_name'),
                    'express_num'  => I('post.express'),
                    'express_at'   => time()
                ));
            }
            if ($setExpress) {
                //根据订单商品物流信息更改订单状态
                $orderExpress = $orderCollect->where(array('order_id' => I('post.id'), 'express_num' => '0'))->count();
                if ($orderExpress < 1) {
                    //更变订单状态
                    M('OrderEntity')->where(array('order_id' => I('post.id')))->setField(array('order_status' => 2));
                }
                $this->showtips('发货成功');
            } else {
                $this->showtips('操作失败');
            }
        } elseif (I('get.oid')) {
            $oData = M('OrderEntity')
                ->where(array('order_id' => I('get.oid')))->find();
            if ($oData['order_status'] != '1') {
                $this->assign('wmsg', '无效订单号');
            }
            $this->express = explode(',', getSysConfig('expressComp'));
            $this->assign('sData', $oData);
            $this->display('order/send');
        }
    }


    /*
     * 分销_导出订单
     * @date: 2016-04-26 16:17:00
     * @editor: WENCUN
     * */
    public function exportExcel() {
        set_time_limit(0);
        if (IS_POST) {
            if (I('post.dosubmit')) {
                $tableHeader = array(
                    '订单编号', '收货人', '手机号码', '商品ID', '商品名称', '商品规格', '商品数量', '省份', '城市', '详细收货地址', '订单成交时间', '物流公司', '物流运单号', '发货时间', '身份信息'
                );
                //$data[0]=$title;
                if (I('post.dotime') && I('post.endtime')) {
                    $doTime = strtotime(I('post.dotime'));
                    $endTime = strtotime(I('post.endtime'));
                    $shipments = M('OrderEntity')
                        ->field(array(
                            'order_id', 'receive_name', 'receive_mobile', 'receive_provice', 'receive_city', 'receive_address', 'add_at', 'receive_identity'
                        ))
                        ->where(array('order_status' => '1', 'order_type' => '0'))
                        ->where('add_at > ' . $doTime . ' and add_at < ' . $endTime)->select();
                }
                //根据订单编号获取订单商品信息(商品标题,商品数量,商品规格)
                foreach ($shipments as $key => $value) {
                    $sql = 'SELECT a.goods_id,a.goods_title,a.goods_attr,a.pay_nums
								FROM fx_order_collect a
								LEFT JOIN fx_goods_entity b
								ON a.goods_id=b.goods_id
								WHERE b.resource=2 AND a.order_id="' . $value['order_id'] . '"';
                    $goodsMsg = CQuery($sql);
                    foreach ($goodsMsg as $k => $v) {
                        $data[] = array(
                            '1'  => strval($value['order_id']),
                            '2'  => $value['receive_name'],
                            '3'  => $value['receive_mobile'],
                            '4'  => $v['goods_id'],
                            '5'  => $v['goods_title'],
                            '6'  => $v['goods_attr'],
                            '7'  => $v['pay_nums'],
                            '8'  => $value['receive_provice'],
                            '9'  => $value['receive_city'],
                            '10' => $value['receive_address'],
                            '11' => date('Y/m/d H:i:s', $value['add_at']),
                            '12' => $v['express_name'],
                            '13' => $v['express_num'],
                            '14' => $value['express_at'] > 0 ? date('Y/m/d H:i:s', $value['express_at']) : '',
                            '15' => $value['receive_identity']
                        );
                    }
                };
                if (!$data) {
                    $this->showtips('没有数据');
                } else {
                    exportExcel($tableHeader, $data);
                }
            }
        }
        $this->display('order/exportexcel');
    }

    /*
     * 分销商城_导出发货单
     * @date: 2016-06-17 14:31:00
     * @editor: yanyan
     * */
    public function exportSend(){
        //根据订单编号查找该订单的发货详情
//获取订单状态等信息 根据订单号获取商品ID 根据商品ID获取商品来源等信息
        $sql = "SELECT DISTINCT(a.order_id),a.order_status,a.refund_expressnum,a.receive_identity,a.remark,a.nickname,a.receive_name,a.receive_mobile,a.remark,a.receive_address,a.order_pay,a.add_at
				FROM fx_order_entity a
				LEFT JOIN fx_order_collect b
				ON a.order_id=b.order_id
				LEFT JOIN fx_goods_entity c
				ON b.goods_id=c.goods_id
				WHERE a.order_type=0 AND a.order_id ='" . I('get.oid') . "' AND c.resource=2";
        $order_send = CQuery($sql);
        $this->assign('order_send',$order_send[0]);
        $this->display('order/exportsend');
    }
    /*
     * 分销商城_导入Excel表格
     * @date: 2016-04-27 17:31:00
     * @editor: WENCUN
     * */
    public function importExcel() {
        if ($_POST) {
            //$url = DIRROOT.'/statics'.'/upload/image/20160428/20160428080010_23634.xls';
            $url = DIRROOT . '/statics' . I('post.xls_url');
            $data = importExcel($url);
            $param = array();
            if ($data) {
                foreach ($data as $key => $value) {
                    $orderStatus = M('OrderEntity')
                        ->where(array('order_id' => $value['订单编号'], 'order_status' => '1', 'order_type' => '0'))->count();
                    if ($value['物流运单号'] && $orderStatus > 0) {
                        $param[] = array(
                            'order_id'     => $value['订单编号'],
                            'goods_id'     => $value['商品ID'],
                            'express_name' => $value['物流公司'],
                            'express_num'  => $value['物流运单号'],
                        );
                    }
                }
            }
            if ($param) {
                $succ = 0;
                foreach ($param as $key => $value) {
                    if ($value['express_num']) {
                        //@todo 扣除对应仓库商品的库存量

                        $setExpress = M('OrderCollect')
                            ->where(array('order_id' => $value['order_id'], 'goods_id' => $value['goods_id']))->setField(array(
                                'express_name' => $value['express_name'],
                                'express_num'  => $value['express_num'],
                                'express_at'   => time()
                            ));
                        //如果当前的订单与下一个订单不相同则更新订单状态
                        if ($param[$key]['order_id'] != $param[$key + 1]['order_id']) {
                            //根据订单商品物流信息更改订单状态
                            $orderExpress = M('OrderCollect')
                                ->field('express_num')->where(array('order_id' => $value['order_id'], 'express_at' => '0'))->count();
                            if (!$orderExpress) {
                                //更变订单状态
                                M('OrderEntity')
                                    ->where(array('order_id' => $value['order_id'], 'order_status' => '1'))->setField(array(
                                        'order_status' => 2,
                                        'update_at'    => time()
                                    ));
                            }
                        }
                        if ($setExpress)
                            $succ++;
                    }
                }
                if ($setExpress) {
                    $this->showtips('成功导入' . $succ . '条物流信息');
                } else {
                    $this->showtips('操作失败');
                }
            } else {
                $this->showtips('数据有误');
            }
        }
        $this->display('/order/importexcel');
    }

    /*
     * 查看物流
     * @date: 2016-06-14 13:57:00
     * @editor: GaoChao
     */
    public function showExpress() {
        if (I('post.dosubmit') && I('post.order_id')) {
            $data = array(
                'express_num'    => I('post.express_num'),
                'update_at' => time()
            );
            $update = $this->_OrderCollectModel->updateOneOrderCollect($data, array('order_id' => I('post.order_id')));
            if ($update) {
                $this->showtips('操作成功');
            } else {
                $this->showtips('操作失败');
            }
        } else {
            if (I('get.order_id')) {
                $express_info = $this->_OrderCollectModel->getOrderCollect(array('express_name', 'express_num', 'express_at'), array('order_id' => I('get.order_id')));
                $this->assign('express_info', $express_info);
            }
            $this->display('/order/express');
        }
    }
}